﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Configuration;
using com.tdb.foundation;
using com.tdb.posion.protocol.protobuf;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class RoomView : BaseView
{
    [SerializeField]
    private Text _roomName;
    [SerializeField]
    private GameObject _memberInfoItemPrefab, _memberInfoItemList;

    private RoomContext _context;
    public override void OnEnter(BaseContext context, UnityAction callback)
    {
        _context = context as RoomContext;
        _roomName.text = _context.RoomName;
    }

    private void OnDestroy()
    {
        _context.Dispose();
    }
}

public class RoomContext : BaseContext
{
    public string RoomName;

    public List<MemberInfo> Members;

    public RoomContext(string roomName) : base(UIType.Room)
    {
        RoomName = roomName;
        NetManager.Instance.RegisterUdpMessageHandler(Cmds.FIND_ROOM, OnReceiveFindRoomReq);
        Members = new List<MemberInfo>();
    }

    public void OnReceiveFindRoomReq(Message msg, IPEndPoint ipEndPoint)
    {
        if (msg.HasExtension(FindRoomReq.Msg))
        {
            FindRoomRes.Builder frrb = FindRoomRes.CreateBuilder();
            RoomInfo.Builder rib = RoomInfo.CreateBuilder().SetMembers(Members.Count).SetName(RoomName);
            frrb.SetRoomInfo(rib.Build());
            ipEndPoint.Port = Const.UdpListenerPort;
            NetManager.Instance.SendUdpMessage(NetUtil.CreateMessage(Cmds.FIND_ROOM, FindRoomRes.Msg, frrb.Build()), ipEndPoint);
        }
    }


    public override void Dispose()
    {
        base.Dispose();
        NetManager.Instance.UnRegisterUdpMessageHandler(Cmds.FIND_ROOM);
    }
}
